var fs = require('fs');//加载fs模块
var path = require('path');//加载path模块
var pagePath = path.join(__dirname, './views');
var imports = [];
var routesNames = [];//生成的路径文件夹
getRoutes(pagePath);//执行方法（在同一块级作用域中，方法定义的位置不影响执行的结果）
//生成文本字符串
var fileString = "const routers = [\n";
routesNames.forEach(function(item,index){
    fileString+="{\n";

    fileString+="path:'/"+item.name+"',\n";
    fileString+="name:'"+item.name+"',\n";
    fileString+="component:(resolve) => require(['"+item.route+"'],resolve),\n";
    fileString+="},\n"
})
fileString+="{\n";

fileString+="path:'*',\n";
fileString+="redirect:'/index',\n";
fileString+="},\n"
fileString+="{\n";

fileString+="path:'/',\n";
fileString+="redirect:'/index',\n";
fileString+="}\n"
fileString += "]\n"
fileString+="export default routers"
//将文本字符串写入到文件中
fs.writeFileSync(path.join(__dirname, './route.js'), fileString);
//文件扫描及生成route数组的方法
function getRoutes(filePath, fileName, modulesName) {
    if (!modulesName) {
        modulesName = fileName;
    }

    var stat = fs.statSync(filePath);
    var isDir = stat.isDirectory();
    if (isDir) {
        var files = fs.readdirSync(filePath)
        if (files && files.length) {
            files.forEach(function (fn, index) {
                var fp = path.join(filePath, fn);
                getRoutes(fp, fn, modulesName);
            });
        }
    } else {
        if (fileName) {
            var pathName = filePath.replace(pagePath, '');
            var routesPath = './views'+pathName;
            if (process.platform.indexOf('win') >= 0) {
                routesPath = routesPath.replace(/\\/g, "\/");
            }
            pathName = pathName.replace('.vue', '');
            pathName = pathName.replace('\\', '');
            routesNames.push({name:pathName.split('\\').join("."),route:routesPath});
        }
    }
}